package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.service.UserFollowService;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        //1.校验
        if(dto==null || dto.getArticleId()==null || dto.getAuthorId()==null || dto.getOperation()<0 || dto.getOperation()>1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登陆
        WmUser user = WmThreadLocalUtil.getUser();
        //user.getId()==0算游客 说明 app用户点击的不登录先看看，这种情况也不允许关注
        if(user==null || user.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.利用redis的set结构 存储 关注集合  和   粉丝集合
        String articleId = dto.getArticleId().toString();//文章id
        String authorId = dto.getAuthorId().toString();//作者id  被关注人id
        String userId = user.getId().toString();//当前登录人id

        //当前登录人 关注了谁
        BoundSetOperations<String, String> followOps = stringRedisTemplate.boundSetOps(BehaviorConstants.APUSER_FOLLOW_RELATION + userId);

        //被关注人 粉丝是谁
        BoundSetOperations<String, String> fansOps = stringRedisTemplate.boundSetOps(BehaviorConstants.APUSER_FANS_RELATION + authorId);

        if(dto.getOperation()==0){//关注
            Boolean member = followOps.isMember(authorId);
            if(member){//说明 当前登录人  已经 关注了  作者
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"请勿重复关注");
            }
            followOps.add(authorId);
            fansOps.add(userId);

        }else{// 取消关注
            Boolean member = followOps.isMember(authorId);
            if(!member){//说明 当前登录人  没有关注过 作者
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"请先关注作者后才能取消");
            }
            followOps.remove(authorId);
            fansOps.remove(userId);

        }

        //3.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
